﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ServerMonitor.Common
{
    public class SqlHelper
    {
       
        /// <summary>
        /// 获取数据库连接数
        /// </summary>
        /// <param name="DbNames">数据库名称，逗号隔开的字符串</param>
        /// <param name="ConStr">数据库连接字符串</param>
        /// <returns></returns>
        public static DataTable GetConnectCount(string DbNames, string ConStr)
        {
            DataTable dt = null;
            string tempSql = @"select count(1) Count,'{0}' Db from master.dbo.sysprocesses where dbid = DB_ID('{0}')  ";

            string Sql = "";
            DbNames.Split(',').ToList().ForEach(a =>
            {
                if (string.IsNullOrEmpty(Sql))
                {
                    Sql += string.Format(tempSql, a);
                }
                else
                { Sql += " union " + string.Format(tempSql, a); }
            });
            try
            {
                dt = new DataTable();
                using (SqlConnection con = new SqlConnection(ConStr))
                {
                    SqlDataAdapter da = new SqlDataAdapter(Sql, con);
                    da.Fill(dt);
                }
            }
            catch (Exception ex)
            {
                dt = new DataTable();
            }
            return dt;
        }
    }
}
 